package com.aaa.security;

import com.aaa.entity.AuthUser;
import com.aaa.entity.ResponseMsg;
import com.aaa.jwt.JwtTokenUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @ClassName: AuthFailHandler
 * @Description: TODO
 * @Author: 86139
 * @Date: 2021/7/28 22:40
 * @Version:1.0
 **/
@Component
public class Chenggong implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        AuthUser authorities = (AuthUser)authentication.getPrincipal();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("authUser",authorities);
        String token = JwtTokenUtils.getToken(hashMap);

        HashMap<Object, Object> map = new HashMap<Object, Object>();
        map.put("token",token);
        map.put("authUser",authorities);
        ResponseMsg msg = new ResponseMsg(HttpServletResponse.SC_OK, "认证成功", map);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.println(JSON.toJSONString(msg));
        writer.flush();
        writer.close();
    }
























}
